﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Core.BOL;
using ScoutNET.Attributes;

namespace ScoutNET.Controllers
{
    [NotFoundErrorAttribute]
    [HandleErrorWithELMAHAttribute]
    public abstract class ApplicationController : Controller
    {
        public ApplicationController()
        {
            ViewData = new ViewDataDictionary {
                {"Master_RSS_Unite", ScoutNET.Resources.Master_RSS_Unite},
                {"Master_RSS_Scout", ScoutNET.Resources.Master_RSS_Scout},
                {"Master_RSS_Pionnier", ScoutNET.Resources.Master_RSS_Pionnier},
                {"Master_RSS_Nuton", ScoutNET.Resources.Master_RSS_Nuton},
                {"Master_RSS_Lutin", ScoutNET.Resources.Master_RSS_Lutin},
                {"Master_RSS_Louveteau", ScoutNET.Resources.Master_RSS_Louveteau},
                {"Master_RSS_Guide", ScoutNET.Resources.Master_RSS_Guide}
            };

            MembershipUser mu = Membership.GetUser();
            string[] userRoles = Roles.GetRolesForUser();

            ViewData["UserRole"] = (userRoles.Length > 0) ? "( " + userRoles[0] + " )" : string.Empty;
            ViewData["UserType"] = UsersRepository.GetUserType();
            
            if (mu != null)
            {
                MyAlbumRepository mr = new MyAlbumRepository();

                int userCountImage = mr.GetCountImagesByUserID((Guid)mu.ProviderUserKey);
                ViewData["UserCountImage"] = (!string.IsNullOrEmpty(userCountImage.ToString())) ? "( " + userCountImage.ToString() + " )" : string.Empty;
            }
        }

        protected override void HandleUnknownAction(string actionName)
        {
            try
            {
                this.View(actionName).ExecuteResult(this.ControllerContext);
            }
            catch (InvalidOperationException ieox)
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Error_Error404_Breadcrumb;

                ViewData["Breadcrumb"] = saBreadcrumb;
                ViewData["PageTitle"] = Resources.Error_Error404_Title;
                ViewData["PageDescription"] = Resources.Error_Error404_Description;

                Response.TrySkipIisCustomErrors = true;
                Response.StatusDescription = "Not Found";
                Response.StatusCode = 404;

                ViewData["error"] = "Unknown Action: \"" + Server.HtmlEncode(actionName) + "\"";
                ViewData["exMessage"] = ieox.Message;
                this.View("Error404").ExecuteResult(this.ControllerContext);
            }
        }
    }
}
